import React, { useEffect, useState } from "react";
import style from "./create.module.css";
import { SideBar } from "antd-mobile";
import { Drawer } from "antd";
import Picture from "./Picture/index";
import Upload from "./Upload/index";
import Writing from "./Writing/index";
import Background from "./Background/index";
import { Resizable } from "re-resizable";
import "react-quill/dist/quill.snow.css";
import { editorCenter } from "../../mock/commAttr";
import ContexteMenu from "./ContexteMenu";
import { useDispatch, useSelector } from "react-redux";
import {
  addItem,
  addcurrentcomponent,
  setCurrItemId,
  setCurrItemId1,
} from "../../store/module/listSlice";
import Parent from "../../mock/Parent";
import Material from "./Material/index";
import { useNavigate } from "react-router-dom";
import Top from "./Top";
import Cropper from "../../compoents/Crop/cropper";
import { Watermark } from "antd";
import { SignatureOutlined } from "@ant-design/icons";
import { Modal, Select } from "antd";
import Message from "../../compoents/Message/message";

function Index() {
  // 左侧数据
  const commponentsData = useSelector((state) => state.list.commponentsData);
  // 拖拽的数据
  const info = useSelector((state) => state.list.dargInfo);
  //
  const dispatch = useDispatch();
  // 中间画布的所有数据读取 push
  const componentList = useSelector((state) => state.list.componentList);
  // 当前拖拽的数据
  const currentcomponent = useSelector((state) => state.list.currentcomponent);
  // 当前 id
  const currentCptId = useSelector((state) => state.list.currentCptId);
  // 菜单
  const menuInfo = useSelector((state) => state.list.menuInfo);
  // 状态处理裁剪
  const [showCropper, setShowCropper] = useState(false);
  const [imageScale, setImageScale] = useState(1);
  // 定义裁剪组件的图片URL状态及更新函数
  const [cropperImageUrl, setCropperImageUrl] = useState("");
  // 新增状态用于存储创客贴高度
  const [watermarkHeight, setWatermarkHeight] = useState(200);
  // 控制水印显示的状态
  const [showWatermark, setShowWatermark] = useState(true);

  // 存储输入框的值
  const [widthValue, setWidthValue] = useState("0");
  const [heightValue, setHeightValue] = useState("0");

  // 左侧 的tab 切换
  const tabs = [
    {
      key: "key1",
      title: "上传",
    },
    {
      key: "key2",
      title: "模版",
    },
    {
      key: "key3",
      title: "素材",
    },
    {
      key: "key4",
      title: "文字",
    },
    {
      key: "key5",
      title: "图片",
    },
    {
      key: "key6",
      title: "背景",
    },
    {
      key: "key7",
      title: "组件",
    },
    {
      key: "key8",
      title: "AI 工具",
    },
  ];
  // 抽屉是否打开
  const [open, setOpen] = useState(true);
  const [currentContent, setCurrentContent] = useState(
    localStorage.getItem("uploadkey")
  );

  const renderContent = () => {
    switch (currentContent) {
      case "key1":
        return <Upload />;
      case "key2":
        return <div>模版内容</div>;
      case "key3":
        return <Material />;
      case "key4":
        return <Writing />;
      case "key5":
        return <Picture />;
      case "key6":
        return <Background />;
      case "key7":
        return <div>组件内容</div>;
      case "key8":
        return <div>AI 工具内容</div>;
      default:
        return <div>请选择一个选项</div>;
    }
  };

  // tab 切换方法
  const showDrawer = (key: string) => {
    console.log(key);

    setCurrentContent(key); // 设置当前选中的标签
    setOpen(true);
    localStorage.setItem("uploadkey", key);
  };

  // 关闭弹框
  const back = () => {
    setOpen(false);
  };

  // 打开弹框
  const opentan = () => {
    setOpen(true);
  };

  // 拖动目标元素事件=》必须要有=》否则无法触发结束
  const dragover = (e: any) => {
    // 阻止默认行为
    e.preventDefault();
  };

  const navigate = useNavigate();
  const backto = () => {
    navigate("/home");
  };

  // 点击空白区域鼠标右键事件
  const clickHandle = (event: any) => {
    // 阻止默认的右键菜单
    event.preventDefault();
    dispatch(setCurrItemId(null));
  };

  const [rotation, setRotation] = useState(0);

  // 放大图片函数
  const zoomIn = () => {
    setImageScale((prevScale) => prevScale + 0.1);
  };

  // 缩小图片函数
  const zoomOut = () => {
    setImageScale((prevScale) => Math.max(prevScale - 0.1, 0.1));
  };

  // 弹框
  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = () => {
    setIsModalOpen(true);
    setShowCropper(true);
    if (draggedImageUrl) {
      setCropperImageUrl(draggedImageUrl);
      console.log("Setting cropper image URL:", draggedImageUrl);
    }
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // 监听componentList的变化，更新创客贴高度
  useEffect(() => {
    const updataWatermarkHeight = () => {
      const centerElement = document.querySelector(".center");
      if (centerElement) {
        const height = centerElement.clientHeight;
        setWatermarkHeight(height);
      }
    };
    updataWatermarkHeight();
    return () => {
      // 清理函数
    };
  }, [componentList]);

  // 鼠标点击
  useEffect(() => {
    document
      .querySelector(".center")
      ?.addEventListener("contextmenu", clickHandle);
    return () => {
      document
        .querySelector(".center")
        ?.removeEventListener("contextmenu", clickHandle);
    };
  }, []);

  // 点击出现评论盒子
  const toggleSayBox = () => {
    // setShowSayBox(!showSayBox);
  };

  // 监听画布大小的变化
  useEffect(() => {
    // const updateWatermarkAndInputs = () => {
    //   const centerElement = document.querySelector(".center");
    //   if (centerElement) {
    //     const width = centerElement.clientWidth;
    //     const height = centerElement.clientHeight;
    //     const watermarkElement = document.querySelector(".watermark-layer div");
    //     if (watermarkElement) {
    //       // 根据画布高度动态调整水印字体大小和透明度
    //       watermarkElement.computedStyleMap.fontSize =
    //         Math.min(width / 20, height / 20) + "px";
    //       watermarkElement.computedStyleMap.opacity =
    //         width > 800 && height > 600 ? 0.3 : 0.1;
    //       if (width < 600 || height < 400) {
    //         watermarkElement.computedStyleMap.display = "none";
    //       } else {
    //         watermarkElement.computedStyleMap.display = "block";

    //         // 确保水印在画布内
    //         const watermarkRect=watermarkElement.getBoundingClientRect();
    //         const canvasRect=centerElement.getBoundingClientRect();
    //         if(
    //           watermarkRect.bottom>canvasRect.bottom ||
    //           watermarkRect.right>canvasRect.right||
    //           watermarkRect.top<canvasRect.top||
    //           watermarkRect.left<canvasRect.left
    //         ){
    //           // 调整水印位置，使其在画布内
    //           watermarkElement.computedStyleMap.top=Math.min(Math.max(0,height-watermarkElement.clientHeight),height-20)+"px";
    //           watermarkElement.computedStyleMap.right=Math.min(Math.max(0,width-watermarkElement.clientWidth),width-20)+"px"
    //         }
    //       }
    //     }
    //     setWidthValue(`${width}`);
    //     setHeightValue(`${height}`);
    //   }
    // };

    // 强制设置水印状态为true
    const updateWatermarkAndInputs = () => {
      const centerElement = document.querySelector(".center");
      if (centerElement) {
        const width = centerElement.clientWidth;
        const height = centerElement.clientHeight;
        const watermarkElement = document.querySelector(".watermark-layer div");
        if (watermarkElement) {
          // 根据画布高度动态调整水印字体大小和透明度
          watermarkElement.computedStyleMap.fontSize =
            Math.min(width / 20, height / 20) + "px";
          watermarkElement.computedStyleMap.opacity =
            width > 800 && height > 600 ? 0.3 : 0.1;
          if (width < 600 || height < 400) {
            watermarkElement.computedStyleMap.display = "none";
          } else {
            watermarkElement.computedStyleMap.display = "block";

            // 确保水印在画布内且不超出画布高度
            const watermarkRect = watermarkElement.getBoundingClientRect();
            const canvasRect = centerElement.getBoundingClientRect();
            if (
              watermarkRect.bottom > canvasRect.bottom ||
              watermarkRect.right > canvasRect.right ||
              watermarkRect.top < canvasRect.top ||
              watermarkRect.left < canvasRect.left
            ) {
              // 调整水印位置，使其在画布内且不超出画布高度
              let newTop = Math.min(
                Math.max(0, height - watermarkElement.clientHeight),
                height - 20
              );
              let newRight = Math.min(
                Math.max(0, width - watermarkElement.clientWidth),
                width - 20
              );
              watermarkElement.computedStyleMap.top = newTop + "px";
              watermarkElement.computedStyleMap.right = newRight + "px";
            }
          }
        }
        setWidthValue(`${width}`);
        setHeightValue(`${height}`);
      }
    };
    setShowWatermark(true);

    const observer = new ResizeObserver(updateWatermarkAndInputs);
    const centerElement = document.querySelector(".center");
    if (centerElement) {
      observer.observe(centerElement);
    }

    return () => {
      if (centerElement) {
        observer.unobserve(centerElement);
      }
    };
  }, []);

  // 拖拽结束此事件在拖动的元素被放置到目标元素上时触发
  let draggedImageUrl = "";
  // 新增状态用于标记图片是否加载完成
  const [imageLoaded, setImageLoaded] = useState(false);
  const dropFun = (event: any) => {
    const { clientX, clientY } = event;
    console.log(clientX, clientY); // 放入的鼠标位置
    const boxcanvas = document.querySelector(".center");

    if (!boxcanvas) return; // 找不到画布则直接返回

    // 获取画布距离视口的位置
    const { left: l, top: t } = boxcanvas.getBoundingClientRect();

    // 鼠标移入到画布内部 鼠标距离画布的距离
    const left = clientX - l;
    const top = clientY - t;

    // 调试输出
    console.log("commponentsData:", commponentsData);
    console.log("info.type:", info.type);

    // 通过仓库查找对应内容
    const datas = commponentsData.find((item) => item.component === info.type);

    // 数据存在性检查
    if (!datas) {
      console.error("未找到对应组件数据", info.type);
      return; // 在这里可以继续执行，或者执行其他逻辑
    }

    // 这样可以避免对原始数据的修改影响到其他地方
    const dataAll = JSON.parse(JSON.stringify(datas));
    if (info.type === "Dimg") {
      dataAll.propLable = info.value;
      const img = new Image();
      img.src = info.value.url;
      img.onload = () => {
        const imgWidth = img.width;
        const imgHeight = img.height;
        const boxcanvas = document.querySelector(".center");
        const canvasWidth = boxcanvas ? boxcanvas.clientWidth : 0;
        const canvasHeight = boxcanvas ? boxcanvas.clientHeight : 0;
        let scaleX = canvasWidth / imgWidth;
        let scaleY = canvasHeight / imgHeight;
        let scale = Math.min(scaleX, scaleY);
        dataAll.style = {
          ...datas.style,
          ...info.value.style,
          left: 0,
          top: 0,
          width: imgWidth * scale,
          height: imgHeight * scale,
        };
        draggedImageUrl = info.value.url;
        setCropperImageUrl(draggedImageUrl);
        console.log("Dragged image URL:", draggedImageUrl);
        console.log("Setting cropperImageUrl", cropperImageUrl);
        // 设置图片加载完成标志
        setImageLoaded(true);
      };
    } else if (info.type === "Dtext") {
      dataAll.propLable = info.value.text;
      dataAll.style = {
        ...datas.style,
        ...info.value.style,
        left,
        top,
      };
    }

    // 检查水印状态
    if (showWatermark === false) {
      setShowWatermark(true);
    }

    dataAll.id = `id${new Date().getTime()}`;
    dispatch(addItem(dataAll));
    dispatch(addcurrentcomponent(dataAll));
  };

  // 点击按钮去除水印
  const block = () => {
    console.log("去除水印");
    setShowWatermark(false);
  };

  // 存储评论
  const [commentInput, setCommentInput] = useState("");
  // 用于储所有评论
  const [comments, setComments] = useState([]);
  // 提交评论函数
  const submitComment = () => {
    if (commentInput.trim()) {
      setComments([...comments, { text: commentInput, replies: [] }]); //将新评论添加到评论数组中
      setCommentInput(""); //清空输入框
    }
  };

  // 删除评论
  const deleteComment = (index) => {
    const newComments = comments.filter((_, i) => i !== index);
    setComments(newComments);
  };

  // 提交回复的函数
  const submitReply = (index, replyInput) => {
    if (replyInput.trim()) {
      const newComments = [...comments];
      newComments[index].replies.push(replyInput);
      setComments(newComments);
    }
  };

  // 控制分享预览的显示状态
  const [isPreviewVisible, setIsPreviewVisible] = useState(false);
  // 存储生成的分享链接
  const [shareLink, setShareLink] = useState("");
  const [isModalOpen1, setIsModalOpen1] = useState(false);

  const handleOk1 = () => {
    // 保存图片逻辑
    if (draggedImageUrl) {
      const canvas = document.querySelector(".center");
      if (canvas) {
        // 获取画布的dataURL
        const dataURL = canvas.querySelector("image/png");
        const a = document.createElement("a");
        a.href = dataURL;
        a.download = "dragged_image.png";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      }
    }
    setIsModalOpen1(false);
  };

  const handleCancel1 = () => {
    setIsModalOpen1(false);
  };
  const generateShareLink = () => {
    setIsModalOpen1(true);
    const link =
      "https://example.com/share?comment=" +
      encodeURIComponent("这是一个分享的内容");
    setShareLink(link);
    setIsPreviewVisible(true);
  };

  // 下载
  const [isModalOpen2, setIsModalOpen2] = useState(false);
  const download = () => {
    setIsModalOpen2(true);
  };
  const handleOk2 = () => {
    setIsModalOpen2(false);
  };

  const handleCancel2 = () => {
    setIsModalOpen2(false);
  };
  const { Option } = Select;
  // 默认格式
  const [imgFormat, setImgFormat] = useState("jpg");
  // 默认尺寸
  const [imgSize, setImgSize] = useState("1024x1024");
  // 默认压缩
  const [imgZip, setImgZip] = useState("原图无压缩");
  const handleFormatChange = (value) => {
    setImgFormat(value);
  };
  const handleSizeChange = (value) => {
    setImgSize(value);
  };

  return (
    <div className={style.createbox}>
      <div className={style.top}>
        <img
          onClick={backto}
          src="	https://static.chuangkit.com/tools/pc-design/prod/6b2ca6b0a35fc0fabffd.svg"
        ></img>
        {/* <Caozuo /> */}
        <div className={style.btn}>
          <button className={style.btn1}>开通会员</button>
          <button className={style.btn2} onClick={generateShareLink}>
            分享
          </button>
          <Modal open={isModalOpen1} onOk={handleOk1} onCancel={handleCancel1}>
            {isPreviewVisible && (
              <div className={style.sharePreview}>
                <h3>分享链接预览</h3>
                <input
                  type="text"
                  value={shareLink}
                  readOnly
                  className={style.shareLinkInput}
                ></input>
                <button
                  className={style.copyButton}
                  onClick={() => {
                    navigator.clipboard.writeText(shareLink);
                    alert("链接已复制到剪贴板！");
                  }}
                >
                  复制链接
                </button>
                <button
                  className={style.closeButton}
                  onClick={() => setIsPreviewVisible(false)}
                >
                  关闭
                </button>
                {imageLoaded && (
                  <img
                    src={draggedImageUrl}
                    alt="Dragged Image"
                    style={{ maxWidth: "100%", maxHeight: "300px" }}
                  ></img>
                )}
              </div>
            )}
          </Modal>
          <div className={style.icon}>
            <SignatureOutlined className={style.icon} onClick={toggleSayBox} />
            <div className={style.say}>
              <div className={style.message}>
                {comments.map((comment, index) => (
                  <div key={index} className={style.comment}>
                    <span className={style.originalComment}>
                      {comment.text}
                    </span>
                    <button
                      className={style.deleteButton}
                      onClick={() => deleteComment(index)}
                    >
                      删除
                    </button>
                    <div className={style.replies}>
                      {comment.replies.length > 0 &&
                        comment.replies.map((reply, replyIndex) => (
                          <p key={replyIndex} className={style.reply}>
                            {reply}
                          </p>
                        ))}
                    </div>
                    <input
                      placeholder="回复此评论"
                      className={style.replyInput}
                      onKeyDown={(e) => {
                        if (e.key === "Enter") {
                          submitReply(index, e.target.value);
                          e.target.value = "";
                        }
                      }}
                    ></input>
                  </div>
                ))}
              </div>
              <div className={style.send}>
                <input
                  placeholder="发表评论"
                  className={style.shu}
                  value={commentInput} //绑定输入框的数据
                  onChange={(e) => setCommentInput(e.target.value)}
                ></input>
                <button className={style.ping} onClick={submitComment}>
                  提交评论
                </button>
              </div>
            </div>
          </div>
          <button className={style.btn3} onClick={download}>
            下载
          </button>
          <Modal
            title="下载"
            open={isModalOpen2}
            onOk={handleOk2}
            onCancel={handleCancel2}
          >
            <label style={{ marginRight: 10 }}>文件类型:</label>
            <div style={{ display: "flex" }}>
              <Select
                defaultValue={imgFormat}
                onChange={handleFormatChange}
                style={{ width: 220 }}
              >
                <Option value="jpg">JPG</Option>
                <Option value="png">PNG</Option>
                <Option value="gif">GIF</Option>
              </Select>
              <div style={{ marginRight: 10, marginLeft: 20 }}>
                <Select
                  defaultValue={imgSize}
                  onChange={handleSizeChange}
                  style={{ width: 120 }}
                >
                  <Option value="800x600">800x600</Option>
                  <Option value="1024x768">1024x768</Option>
                  <Option value="1920x1080">1920x1080</Option>
                </Select>
              </div>
            </div>
            <Select defaultValue={imgZip} style={{ width: 220, marginTop: 10 }}>
              <Option value="20MB内">20MB内</Option>
              <Option value="10MB内">10MB内</Option>
              <Option value="5MB内">5MB内</Option>
              <Option value="500KB内">500KB内</Option>
              <Option value="200KB内">200KB内</Option>
              <Option value="自定义">自定义</Option>
            </Select>
            <br />
            <button className={style.pel}>
              会员低至0.4元/天，解锁全站内容无水印下载。立即开通
            </button>
            <div className={style.dbtn}>
              <button className={style.dbtn1}>单次下载￥35</button>
              <button className={style.dbtn2}>开通会员无水印下载</button>
            </div>
          </Modal>
        </div>
      </div>
      <div className={style.main}>
        <div className={style.left}>
          <div className={style.lefttab}>
            <SideBar
              onChange={showDrawer}
              style={{ width: "80px" }}
              defaultActiveKey={currentContent}
            >
              {tabs.map((item) => (
                <SideBar.Item key={item.key} title={item.title} />
              ))}
            </SideBar>
          </div>
        </div>
        <div className={style.right}>
          {/* 右边左边弹框 */}
          {open && (
            <div style={{ width: "320px", height: "100%" }}>
              <Drawer
                headerStyle={{ display: "none" }} // 隐藏标题
                open={open}
                placement="left"
                mask={false}
                maskClosable={true}
                contentWrapperStyle={{ boxShadow: "none" }}
                style={{
                  overflow: "auto",
                  marginLeft: "80px",
                  width: "320px",
                  marginTop: "50px",
                  height: "94.5%",
                }}
              >
                <div style={{ height: "780px" }}>{renderContent()}</div>
                <div className={style.back} onClick={back}>
                  &lt;
                </div>
              </Drawer>
            </div>
          )}
          {/* 右边内容 */}
          <div className={style.rightcenter}>
            {/* <Canvas /> */}
            <div
              className={style.bian}
              style={{ border: "none", display: "flex", alignItems: "center" }}
            >
              <Top></Top>
              <div>
                <span
                  onClick={zoomIn}
                  style={{ cursor: "pointer", marginLeft: "15px" }}
                >
                  放大
                </span>
                <span
                  onClick={zoomOut}
                  style={{ cursor: "pointer", marginLeft: "15px" }}
                >
                  缩小
                </span>
                <span
                  onClick={showModal}
                  style={{ cursor: "pointer", marginLeft: "15px" }}
                >
                  裁剪
                </span>
              </div>
            </div>
            {/* 弹框 */}
            <Modal
              title="裁剪"
              open={isModalOpen}
              onOk={handleOk}
              onCancel={handleCancel}
            >
              <Cropper imgUrl={cropperImageUrl}></Cropper>
            </Modal>
            <div className={style.bu}>
              宽:
              <input
                style={{ marginLeft: 5, marginRight: 15 }}
                value={widthValue}
              ></input>
              高:
              <input style={{ marginLeft: 5 }} value={heightValue}></input>
              <Resizable
                className={style.hua}
                defaultSize={{ width: "60%", height: "70%" }}
              >
                <div
                  style={{
                    width: "100%",
                    height: "100%",
                    transform: `scale(${imageScale})`,
                  }}
                  className="center"
                  onDragOver={dragover}
                  onDrop={dropFun}
                >
                  {/* 画布数据渲染 */}
                  {showWatermark && (
                    // <Watermark content="创客贴">
                      <div
                        className="watermark-layer"
                        style={{
                          height: watermarkHeight,
                          zIndex: 999999999999999999999,
                          position: "absolute",
                        }}
                      >
                      {componentList.map((item: any, index: number) => {
                        const Cot = editorCenter[item.component];
                        return (
                          <Parent {...item}>
                            {Cot ? (
                              <Cot
                                {...item}
                                style={{
                                  transform: `rotate(${rotation}deg) scale(${imageScale})`,
                                  overflow: "hidden",
                                  objectFit: "contain",
                                }}
                              />
                            ) : null}
                          </Parent>
                        );
                      })}
                      </div>
                    // </Watermark>
                  )}
                  <button className={style.butt} onClick={block}>
                    移除水印,畅享高清模版
                  </button>
                  {/* 鼠标右键菜单 */}
                  {menuInfo.showMenu && <ContexteMenu></ContexteMenu>}
                </div>
              </Resizable>
            </div>
            {/* 问题列表 */}
            <Message></Message>
          </div>
          <div>
            {open ? (
              <div className={style.open} onClick={opentan}>
                &gt;
              </div>
            ) : (
              <div className={style.open} onClick={opentan}>
                &gt;
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

export default Index;
